<!-- 员工管理---员工信息管理页面 -->
<template>
  <div class="xin-xi">
    <Breadcrumb :breadStr="breadStr"></Breadcrumb>
    <!-- 搜索框、录入员工信息按钮 -->
    <el-card
      shadow="hover"
      class="search-and-add"
      :body-style="{ padding: '15px' }"
    >
      <!-- 搜索框所在的行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="查找员工, 支持姓名和员工类型模糊查询"
            v-model="queryInfo.query"
            clearable
            @clear="getYgList"
            @keyup.enter.native="getYgList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getYgList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col
          :span="6"
          class="caozuo"
        >
          <el-button
            type="primary"
            @click="showDialog()"
          >录入员工信息</el-button>
          <el-button
            type="warning"
            size="small"
            @click="importYgVisible = true"
          >导入员工信息</el-button>
          <el-dialog
            title="导入员工信息"
            :visible.sync="importYgVisible"
            width="30%"
          >
            <div class="main-info">
              <p>说明：支持导入xlsx、xls格式Excel表格。请在本站提供的模板文件上增加数据后导入</p>
              <span>模板文件下载: </span>
              <ExcelExport
                class="mubanxiazai"
                ref="excelMubanExport"
                :sheet='sheet'
                :manual="true"
                :filename="exportFileName"
              >
                <el-button
                  type="text"
                  size="mini"
                  @click="exportMubanTable('excelMubanExport')"
                >下载模板</el-button>
              </ExcelExport>
            </div>
            <ExcelImport :on-success="importSuccess">
              <el-button
                type="warning"
                size="small"
                @click="importYgVisible = true"
              >导入</el-button>
            </ExcelImport>
          </el-dialog>
          <ExcelExport
            ref="excelExport"
            :sheet='sheet'
            :manual="true"
            :filename="exportFileName"
          >
            <el-button
              v-if="!isSelection"
              type="warning"
              size="small"
              @click="isSelection = true"
            >导出员工信息</el-button>
            <div
              class="export-btn"
              v-else
            >
              <el-button
                type="success"
                size="small"
                @click="preExportTable()"
              >确认导出</el-button>
              <el-button
                type="text"
                size="mini"
                @click="cancelExport()"
              >取消导出</el-button>
            </div>
          </ExcelExport>
        </el-col>
      </el-row>
      <YuangongDetail></YuangongDetail>
    </el-card>
    <!-- 展示员工信息的表格，以及下面的分页条 -->
    <el-card
      shadow="hover"
      class="information-list"
      :body-style="{ padding: '20px' }"
    >
      <el-table
        :data="ygList"
        border
        stripe
        ref="ygListTable"
        :default-sort="{prop: 'enterdata', order: 'descending'}"
        style="width:100%"
        @selection-change="selectionChange"
      >
        <template slot="empty">
          <p>没有任何员工信息，请先录入/导入</p>
        </template>
        <el-table-column
          v-if="isSelection"
          type="selection"
          width="40"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="enterdata"
          label="入司时间"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="grade"
          label="员工定级"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="category"
          label="员工类别"
          sortable
        >
        </el-table-column>

        <el-table-column
          label="编辑"
          width="180"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            >详情/修改</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="delYg(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 下面分页显示的条条 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        :current-page="queryInfo.pagenum"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <loading
      :active.sync="isLoading"
      color="#409EFF"
      :height=128
      :width=128
      :can-cancel="false"
      :is-full-page="true"
      loader="bars"
    ></loading>
  </div>
</template>

<script>
import Breadcrumb from '../common/Breadcrumb'
import { ExcelExport, ExcelImport } from 'pikaz-excel-js'
import Loading from 'vue-loading-overlay'
import 'vue-loading-overlay/dist/vue-loading.css'
import { homeMixin } from '../../utils/mixin'
import YuangongDetail from '../common/YuangongDetail'
export default {
  mixins: [homeMixin],
  components: {
    Breadcrumb, YuangongDetail, ExcelExport, ExcelImport, Loading
  },
  data () {
    return {
      ygList: [],
      total: 0,
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      // 多选框的显示状态
      isSelection: false,
      ygExportData: [],
      exportFileName: '人事信息--甘文崔',
      sheet: [],
      importYgVisible: false,
      tHeader: ['姓名', '性别', '年龄', '身份证号码', '籍贯', '家庭住址',
        '毕业院校', '学历', '入司时间', '离职时间',
        '部门名称', '岗位', '类别', '人员定级', '办公地点'],
      keys: ['name', 'gender', 'age', 'idcard', 'jiguan', 'address',
        'school', 'xueli', 'enterdata', 'outdata',
        'bumen', 'gangwei', 'category', 'grade', 'workaddr'],
      isLoading: false
    }
  },
  created () {
    this.getBread()
    this.getYgList()
  },
  methods: {
    // 显示添加员工信息的对话框
    showDialog () {
      this.setIsAdd(true)
      this.setYuangongForm({})
      this.setYuangongDialogVisible(true)
    },
    async getYgList () {
      const { data } = await this.$http.get('/yg/getlist',
        {
          params:
          {
            pagenum: this.queryInfo.pagenum,
            pagesize: this.queryInfo.pagesize,
            query: this.queryInfo.query
          }
        })
      if (data.error_code === 0) {
        if (data.count > 0) {
          this.ygList = data.data
          this.total = data.count
          // 处理时间格式字符串
          this.ygList = this.dealTime(JSON.stringify(this.ygList), 'enterdata')
        } else {
          console.log('查询结果为空')
        }
      } else {
        console.log('数据获取失败')
      }
    },
    // 根据id删除单条员工信息
    delYg (index, row) {
      this.$MessageBox.confirm('此操作将永久删除该员工信息，是否继续？', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        const { data } = await this.$http.post('/yg/del', { ygid: row.id })
        if (data.error_code === 0) {
          this.$message.success('删除成功')
          this.ygList = this.ygList.filter(item => {
            return item.id !== row.id
          })
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 查看招聘详情/修改员工信息
    async handleEdit (index, row) {
      this.setIsAdd(false)
      const data = await this.queryOne(row.id)
      if (!data) {
        return
      }
      this.setYuangongForm(data)
      this.setYuangongDialogVisible(true)
    },
    // 传入员工id，获取该员工详细信息，获取失败返回空
    async queryOne (id) {
      const { data } = await this.$http.get('/yg/queryone', {
        params: {
          ygid: id
        }
      })
      if (data.error_code !== 0) {
        console.log('获取失败')
        return
      }
      data.data.enterdata = data.data.enterdata.split('T')[0]
      if (data.data.outdata) {
        data.data.outdata = data.data.outdata.split('T')[0]
      }
      return data.data
    },
    // pagesize改变事件,每页显示条数更改
    handleSizeChange (newPageSize) {
      this.queryInfo.pagesize = newPageSize
      this.getYgList()
    },
    // pagenum改变事件，当前页码修改
    handleCurrentChange (newPageNum) {
      this.queryInfo.pagenum = newPageNum
      this.getYgList()
    },
    // 表格导出前的预处理
    preExportTable () {
      if (this.ygExportData.length < 1) {
        this.$message.error('请选择要导出的员工项')
        return
      }
      const table = this.ygExportData
      console.log(table)
      this.sheet = [{
        title: this.exportFileName,
        tHeader: this.tHeader,
        table,
        keys: this.keys,
        sheetName: this.exportFileName,
        cellStyle: [
          {
            cell: 'A1',
            font: {
              name: '宋体',
              sz: 16,
              bold: true
            },
            fill: {
              fgColor: { rgb: 'ff7e00' }
            }
          }
        ]
      }]
      this.exportTable('excelExport')
    },
    // 改变导出选中项
    async selectionChange (val) {
      if (val.length < 1) {
        this.ygExportData = []
        return
      }
      this.ygExportData = []
      for (const item of val) {
        const data = await this.queryOne(item.id)
        // 数据格式相关处理
        if (!data.outdata) {
          data.outdata = ''
        }
        // 非离职的员工离职时间，默认写的是这个时间
        if (data.outdata === '1999-01-01') {
          data.outdata = ''
        }
        this.ygExportData.push(data)
      }
    },
    // 导出员工信息为excel
    exportTable (ref) {
      this.$refs[ref].pikaExportExcel()
      // ASK 导出成功后，取消导出这语义好像不合适(或者给cancelExport换个名字)
      setTimeout(() => {
        this.cancelExport()
      }, 2000)
    },
    cancelExport () {
      this.isSelection = false
      this.$refs.ygListTable.clearSelection()
    },
    // 员工信息导入成功
    async importSuccess (res, file) {
      this.importYgVisible = false
      this.isLoading = true
      if (res.length > 1 || res[0].sheetName !== this.exportFileName) {
        this.$message.error('导入的文件不符合要求，请使用本站提供的模板文件修改后导入')
      }
      const inputdata = res[0]?.data
      // const afterDealwithData = []
      // 数据处理，变成table格式的
      for (const [index, item] of inputdata.entries()) {
        if (index === 0) {
          continue
        }
        console.log(item)
        const _ = {
          gender: item[''] - 0,
          name: item[this.exportFileName],
          // TODO 下面这些，应该可以简化一下this.keys 中存有前面的字段
          age: item._1 - 0,
          // ASK 测试时候，避免重复，身份证号码手动改变一下
          idcard: item._2 + 111111111,
          jiguan: item._3,
          address: item._4,
          school: item._5,
          xueli: item._6,
          bumen: item._9,
          gangwei: item._10,
          category: item._11,
          grade: item._12,
          workaddr: item._13
        }
        // TODO 筛选重复的。筛选条件：身份证号码重复
        // 获取所有员工的身份证号码
        // TODO 后端给个接口(安全性不好，前端慢慢遍历吧)
        // 调用接口，添加到数据库
        try {
          await this.$http.post('/yg/add', { ..._ })
        } catch (error) {
          // 重复的，导入失败
          console.log(error)
        }
        // afterDealwithData.push(_)
      }
      await this.getYgList()
      this.isLoading = false
      this.$message.success('上传成功')
    },
    // 导出模板文件
    exportMubanTable (ref) {
      const table = [{
        name: '张三(此条记录为举例请删除)',
        gender: '1或0(1代表男，0代表女)',
        age: 20,
        idcard: '340101199110017112',
        jiguan: '广东广州',
        address: '福建南平',
        school: '南平大学',
        xueli: '硕士',
        enterdata: '2020-11-27',
        outdata: '在职员工请留空',
        bumen: '设计',
        gangwei: 'UI设计',
        category: '设计',
        grade: 'P8',
        workaddr: '南平'
      }]
      this.sheet = [{
        title: this.exportFileName,
        tHeader: this.tHeader,
        table,
        keys: this.keys,
        sheetName: this.exportFileName,
        cellStyle: [
          {
            cell: 'A1',
            font: {
              name: '宋体',
              sz: 16,
              bold: true
            },
            fill: {
              fgColor: { rgb: 'ff7e00' }
            }
          }
        ]
      }]
      this.exportTable(ref)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin";
.search-and-add {
  margin-bottom: $elcardbottom;
}
.information-list {
}
.el-pagination {
  margin-top: 20px;
}
.excel-import {
  width: fit-content;
}
.caozuo {
  display: flex;
  .excel-export {
    margin-left: 10px;
    margin-right: 10px;
    // background: #e6a23c;
    line-height: 40px;
    .el-button--warning {
      height: 40px;
    }
    .el-button--success {
      height: 40px;
    }
    .el-button--text {
      background-color: #f56c6c;
      color: #fff;
      width: 80px;
    }
  }
  /deep/.main-info {
    .mubanxiazai {
      display: inline;
      .el-button--text {
        background-color: #409eff;
        color: #fff;
        width: 80px;
      }
    }
  }
  .export-btn {
    display: flex;
  }
}
</style>
